package cn.itcast.service.impl;

import cn.itcast.enums.Constants;
import cn.itcast.service.LoginService;
import cn.itcast.template.SmsTemplate;
import cn.itcast.utils.MD5Utils;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import java.time.Duration;
import cn.itcast.dao.LoginDao;
import cn.itcast.entity.Result;
import cn.itcast.pojo.User;
import java.util.Map;


@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Autowired
    private LoginDao loginDao;


    /**
     * 发送验证码
     *
     * @param phone
     * @return
     */
    public Boolean sendSmsToPhone(String phone) {
        //判断手机号是否为空,返回false
        if (phone == null) {
            return false;
        }
        //定义验证码(方便之后测试)
        String code = "123456";
        //调用模板类发送验证码
        //smsTemplate.sendSms(phone,code); //为方便测试 写死验证码 直接存到redis中
        //拼接key,存入redis
        String redisKey = Constants.SMS_CODE + phone;

        redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));
        //返回true
        return true;
    }

    public static void main(String[] args) {

        System.out.println(MD5Utils.md5("123456"));

    }


    /**
     * //登陆
     * @param map
     * @return
     */
    @Override
    public Result login(Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        User user = loginDao.findByUsername(username);
        String username1 = user.getUsername();
        String password1 = user.getPassword();
        String md5Password = MD5Utils.md5(password);
        System.out.println("md5Password = " + md5Password);
        System.out.println(user);
        System.out.println("password1 = " + password1);
        if (username.equals(username1) && password1.equals(md5Password)) {
            return new Result(true, "信息验证成功");
        } else {
            return new Result(false, "账号密码有误，请重新输出入");
        }
    }
}





